import React from 'react'
import { List, Button, Skeleton, message, Avatar } from 'antd'
import Component, { mapStateToProps, mapDispatchToProps } from '@components/Component'
import { connect } from 'react-redux'
import moment from 'moment'
import style from './Message.module.less'
import { updateUncompleteMessage } from '../../../redux/actions'

class MessageBlock extends Component {
  state = {
    messageLoading: false,
    messageList_1: [],
    messageList_2: [],
    messageList_3: [],
    messageListSize_1: 0,
    messageListSize_2: 0,
    messageListSize_3: 0,
    messageType: '组庭呈批'
  }

  // 打开消息列表
  openMessageList () {
    this.props.addWindow({ id: 'MessageList', title: '消息列表', componentName: 'MessageList' })
  }

  // 格式化通知信息
  formatMessageList () {
    const type = this.state.messageType
    let list = []
    if (type === '组庭呈批') {
      list = this.state.messageList_1
    } else if (type === '结案文书呈批') {
      list = this.state.messageList_2
    } else {
      list = this.state.messageList_3
    }
    list.forEach(li => {
      if (li.gender === '女') {
        li.color = 'female'
      }
    })
    return list
  }

  // 处理消息回调
  toDealHandle (d) {
    let route = d.route ? d.route : null
    if (!route) {
      return message.warning('处理地址不存在')
    }
    try {
      route = JSON.parse(route)
    } catch (e) {
      return message.warning('获取处理地址错误')
    }
    const component = route.component || route.type
    if (component === 'caseDetail') {
      const { id, operate } = route.meta
      this.props.addWindow({ id: `CaseDetail-${id}`, title: `案件详情-${route.title}`, componentName: 'CaseDetail', forceRefresh: false, meta: { id, operate, editable: true } })
    }
    this.setMessageReaded(d.read_datetime, d.id)
  }

  formatDate (date) {
    if (!date) {
      return date
    }
    return moment(date * 1000).format('YYYY-MM-DD HH:mm')
  }

  // 获取消息列表
  getMessageList (type, index) {
    const condition = [{ k: 'complete_datetime', o: 'null' }]
    if (type === '其他') {
      condition.push({ k: 'title', o: 'not in', v: '立案呈批,组庭呈批,结案文书呈批' })
    } else if (type === '组庭呈批') {
      condition.push({ k: 'title', o: 'in', v: '组庭呈批' })
    } else {
      condition.push({ k: 'title', o: '=', v: type })
    }
    return this.$get('/api/xapc/message', {
      current: 1,
      page_size: 5,
      condition: JSON.stringify(condition)
    }).then(res => {
      if (res.status === 1) {
        this.setState({
          [`messageList_${index}`]: res.data.list,
          [`messageListSize_${index}`]: res.data.total
        })
      } else {
        message.warning(res.message)
      }
    })
  }

  // 获取全部数据信息
  getAllMessageList () {
    this.setState({ messageLoading: true })
    this.timer && clearTimeout(this.timer)
    Promise.all([
      this.getMessageList('组庭呈批', '1'),
      this.getMessageList('结案文书呈批', '2'),
      this.getMessageList('其他', '3')
    ]).then(() => {
      this.setState({ messageLoading: false })
      this.timer = setTimeout(() => {
        this.getAllMessageList()
      }, 1000 * 60)
    }).catch(() => this.setState({ messageLoading: false }))
  }

  // 设置未读信息未已读
  setMessageReaded (time, id) {
    if (time) { return false }
    this.$put(`/api/xapc/message/read/${id}`)
      .then(res => {
        if (res.status === 1) {
          this.props.updateUncompleteMessage()
          this.getAllMessageList()
        } else {
          message.warning(res.message)
        }
      })
  }

  componentDidUpdate (prev) {
    if (prev.uncompleteNum !== this.props.uncompleteNum) {
      this.getAllMessageList()
    }
  }

  componentDidMount () {
    this.getAllMessageList()
  }

  componentWillUnmount () {
    this.timer && clearTimeout(this.timer)
  }

  // 渲染消息类型
  renderMessageType () {
    // const list = ['组庭呈批', '结案文书呈批', '其他']
    const list = ['组庭呈批']
    const t = this.state.messageType
    return list.map((li, i) => {
      const className = [style['toggle-title-btn']]
      const arr = this.state[`messageList_${i + 1}`]
      const total = this.state[`messageListSize_${i + 1}`]
      if (li === t) {
        className.push(style.active)
      }
      if (arr.length) {
        className.push(style.more)
      }
      return (
        <div
          key={li} className={className.join(' ')} onClick={() => {
            this.setState({
              messageType: li
            })
          }}
        >
          <span>{li}</span>
          {total ? <span className={style['message-total']}>{total > 99 ? 99 : total}</span> : null}
        </div>
      )
    })
  }

  // 渲染头像
  renderAvatar (item, i) {
    let name = item.operator || ''
    const arr = [style.avatar]
    if (item.color) {
      arr.push(style[item.color])
    }
    if (name && name.length > 2) {
      name = name.slice(name.length - 2)
    }
    if (item.ico) {
      return (
        <Avatar shape='square' size={40} className={arr.join(' ')} src={item.ico} />
      )
    }
    return (
      <Avatar shape='square' size={40} className={arr.join(' ')}>{name}</Avatar>
    )
  }

  // 渲染标题
  renderTitle (item) {
    return (
      <span className={style['item-name']} onClick={() => this.toDealHandle(item)}>
        <span>{item.title}</span>
        {item.level ? <span className={style['item-urgency']}>紧急</span> : null}
      </span>
    )
  }

  render () {
    return (
      <div className={style.container}>
        <div className={style['block-title']}>
          <div className={style['block-left-title']}>
            {this.renderMessageType()}
          </div>
          <div className={style.btn} onClick={() => this.openMessageList()}>全部呈批</div>
        </div>
        <div className={style['message-list']}>
          <List
            itemLayout='horizontal' loading={this.state.messageLoading} dataSource={this.formatMessageList()} pagination={false} renderItem={(item, i) => {
              return (
                <List.Item className={style['message-line']} actions={[<Button key='deal' type='link' onClick={() => this.toDealHandle(item)}>查看</Button>]}>
                  <Skeleton avatar title={false} loading={item.loading} active>
                    <List.Item.Meta
                      avatar={this.renderAvatar(item, i)}
                      title={this.renderTitle(item)}
                      description={`${item.content} ${this.formatDate(item.create_datetime)}`}
                    />
                  </Skeleton>
                </List.Item>
              )
            }}
          />
        </div>
      </div>
    )
  }
}

const mapState = mapStateToProps(function (state) {
  return {
    uncompleteNum: state.basic.uncompleteNum
  }
})

const mapDispatch = mapDispatchToProps(function (dispatch) {
  return {
    updateUncompleteMessage: () => dispatch(updateUncompleteMessage(dispatch))
  }
})

export default connect(mapState, mapDispatch)(MessageBlock)
